package report

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/api_models"
	"longmen/server/pkg/db/mysql/models/models_report"
)

type AscribeReport struct {
}

func NewAscribeReport() *AscribeReport {
	return &AscribeReport{}
}

func (s *AscribeReport) InsertDB(req *api_models.AscribeReportReq) error {

	var ascribeReportReq models_report.AscribeReport
	ascribeReportReq.Platform = req.Platform
	ascribeReportReq.AndroidId = req.AndroidId
	ascribeReportReq.PackageName = req.PackageName
	ascribeReportReq.Callback = req.Callback
	ascribeReportReq.Res = req.Res
	err := global.Report().Create(&ascribeReportReq).Error
	if err != nil {
		global.Log.Errorf("ascribeReport InsertDB err:%v", err)
		return err
	}
	return nil
}

func (s *AscribeReport) UpdateResById(id uint, newRes string) error {
	// 只更新 Res 字段
	err := global.Report().
		Model(&models_report.AscribeReport{}).
		Where("id = ?", id).
		Update("res", newRes).Error

	if err != nil {
		global.Log.Errorf("更新 Res 失败: id=%d, err=%v", id, err)
		return fmt.Errorf("ascribeReport UpdateResByAndroidId err: %v", err)
	}

	return nil
}

func (s *AscribeReport) GetReportRecord(androidId string) (*models_report.AscribeReport, error) {
	var record models_report.AscribeReport
	err := global.Report().
		Where("android_id = ?", androidId).
		Last(&record).
		Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		global.Log.Errorf("查询失败: android_id=%s, err=%v", androidId, err)
		return nil, fmt.Errorf("ascribeReport GetReportRecord err: %v", err)
	}
	return &record, nil
}

type AscribeTransform struct {
}

func NewAscribeTransform() *AscribeTransform {
	return &AscribeTransform{}
}

func (s *AscribeTransform) InsertDB(req *api_models.AscribeTransformReq) error {

	var ascribeTransReq models_report.AscribeTransform
	ascribeTransReq.EventType = req.EvenType
	ascribeTransReq.AndroidId = req.AndroidId
	ascribeTransReq.Platform = req.Platform
	ascribeTransReq.Callback = req.Callback
	ascribeTransReq.Res = req.Res
	err := global.Report().Create(&ascribeTransReq).Error
	if err != nil {
		global.Log.Errorf("ascribeTransform InsertDB err:%v", err)
		return err
	}
	return nil
}
